import { createRouter, createWebHashHistory } from "vue-router"
import { RouteRecordRaw } from "vue-router"
import cache from "@/utils/cache"

const routes: RouteRecordRaw[] = [
  {
    path: "/",
    component: () => import("@/views/index/index.vue")
  },
  {
    path: "/index",
    name: "index",
    component: () => import("@/views/index/index.vue")
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login/login.vue")
  },
  // 显示没有改路由显示的组件
  {
    path: "/:pathMatch(.*)*",
    name: "not-found",
    component: () => import("@/views/not-found/not-found.vue")
  }
]

const router = createRouter({
  routes,
  history: createWebHashHistory()
})

// 导航守卫
router.beforeEach((to, form, next) => {
  if (to.path !== "/login") {
    const token = cache.getLocation("token")
    if (!token) {
      next({ path: "/login" })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
